package edu.chl.food_store.beans.model;

import edu.chl.food_store.entities.Product;
import edu.chl.food_store.utility.CartItem;
import java.io.Serializable;
import java.util.*;
import javax.faces.bean.*;

/**
 * ShoppingCartModelBean:
 * Keeps track of all the items in the shopping cart.
 */
@ManagedBean
@SessionScoped
public class ShoppingCartModelBean implements Serializable {

    //Shopping cart represented as a list of CartItem.
    private List<CartItem> cart = new LinkedList<CartItem>();

    /**
     * Adds a product to the shopping cart.
     * Increases quantity as required.
     */
    public void addProduct(Product product) {
        Iterator<CartItem> itr = cart.listIterator();
        CartItem item;
        while (itr.hasNext()) {
            item = itr.next();
            if (item.getProduct().equals(product)) {
                item.setQuantity(item.getQuantity() + 1);
                return;
            }
        }
        item = new CartItem(product);
        cart.add(item);
    }

    /**
     * Removes all instances of a product from the cart, regardless of quantity.
     */
    public void removeAll(Product product) {
        Iterator<CartItem> itr = cart.listIterator();
        while (itr.hasNext()) {
            if (itr.next().getProduct().equals(product)) {
                itr.remove();
                return;
            }
        }
    }

    /**
     * Decrease the quantity of a single product.
     * If quantity reaches zero the product is removed completely.
     */
    public void removeOne(Product product) {
        Iterator<CartItem> itr = cart.listIterator();
        CartItem item;
        while (itr.hasNext()) {
            item = itr.next();
            if (item.getProduct().equals(product)) {
                if (item.getQuantity() > 1) {
                    item.setQuantity(item.getQuantity() - 1);
                } else {
                    itr.remove();
                }
                return;
            }
        }
    }

    /**
     * Returns the total accumulated price of the shopping cart. 
     */
    public double getTotalPrice() {
        double total = 0;
        for (CartItem item : cart) {
            total += item.getProduct().getPrice() * item.getQuantity();
        }
        return total;
    }

    /**
     * Number of items in cart.
     */
    public int getSize() {
        int totalQty = 0;
        for (CartItem item : cart) {
            totalQty += item.getQuantity();
        }
        return totalQty;
    }

    /**
     * Empties the shopping cart.
     */
    public void emptyCart() {
        cart.clear();
    }

    public List<CartItem> getCart() {
        return cart;
    }

    public void setCart(List<CartItem> cart) {
        this.cart = cart;
    }
}
